/**
 * 
 */
package com.zaprit.search.support;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;

/**
 * @author Root
 */
public final class SolrIndexer
{
	private Properties	properties	= null;
	private SolrSupport	solrSupport	= null;

	/**
	 * @param properties
	 */
	public SolrIndexer(Properties properties)
	{
		this.properties = properties;
		solrSupport = new SolrSupport(properties);
	}

	/**
	 * used to add list of items in solr document
	 * 
	 * @param scopeId
	 * @param documentList
	 * @param items
	 * @throws Exception
	 */
	public void addSolrDocuments(String scopeId, SolrDocumentList documentList, List<Map<String, Object>> items)
			throws Exception
	{
		SolrServer solrServer = solrSupport.getSolrServer(scopeId);
		for (Map<String, Object> item : items)
		{
			SolrDocument document = new SolrDocument();
			for (Entry<String, Object> entry : item.entrySet())
			{
				document.addField(entry.getKey(), entry.getValue());
			}
			documentList.add(document);
		}

		// solrServer.add(documentList);
	}

	/**
	 * @param query
	 * @return SolrUpdate Response
	 * @throws SolrServerException
	 * @throws IOException
	 */
	public UpdateResponse deleteByQuery(String query) throws SolrServerException, IOException
	{
		UpdateResponse updateResponse = solrSupport.deleteByQuery(query);
		solrSupport.commit();
		return updateResponse;
	}

	/**
	 * @param scopeId
	 * @return true | false
	 * @throws Exception
	 */
	public boolean deleteIndex(String scopeId) throws Exception
	{
		SolrServer solrServer = solrSupport.getSolrServer(scopeId);
		solrServer.deleteByQuery("*:*");
		solrServer.commit();
		return true;
	}
}
